import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");
/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    // 角色【超级管理员】拥有所有权限，忽略校验
    if (roles.includes("ROOT")) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return false;
};

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[]) => {
  	const asyncRoutes: RouteRecordRaw[] = [];
  	routes.forEach((route) => {
		const tmpRoute = { ...route }; // ES6扩展运算符复制新对象
		if (tmpRoute.component?.toString() == "Layout") {
			tmpRoute.component = Layout;
		}else{
			const component = modules[`../../views/${tmpRoute.component}.vue`];
			if (component) {
				tmpRoute.component = component;
			} else {
				tmpRoute.component = modules[`../../views/error-page/404.vue`];
			}
		}
		if (tmpRoute.children) {
			tmpRoute.children = filterAsyncRoutes(tmpRoute.children);
		}
		asyncRoutes.push(tmpRoute);
	});

  return asyncRoutes;
};
// setup
export const usePermissionStore = defineStore("permission", () => {
	// state
	const routes = ref<RouteRecordRaw[]>([]);
	// actions
	function setRoutes(newRoutes: RouteRecordRaw[]) {
		routes.value = constantRoutes.concat(newRoutes);
	}
	
	/**
	 * 生成动态路由
	 *
	 * @param roles 用户角色集合
	 * @returns
	 */
	function generateRoutes() {
		return new Promise<RouteRecordRaw[]>((resolve, reject) => {
		// 接口获取所有路由
		listRoutes()
			.then(res => {
				if (res) {
					let rdata = JSON.parse(JSON.stringify(res.data))
					function parseMeta(obj:any) {
						obj.meta = JSON.parse(obj.meta);
						if (obj.children && obj.children.length > 0) {
							obj.children.forEach((child:any) => {
								parseMeta(child);
							});
						}
					}
					rdata.forEach((item:any)=>{
						parseMeta(item)
					})
					let newRoute = [];

					rdata.forEach((item:any)=>{
						var arr = [];
						item.children.forEach((item2:any)=>{
							var crr = [];
							if(item2.children){
								item2.children.forEach((item3:any)=>{
									const hidden = item3.hidden == 1 ? true : false;

									item3.meta.keepAlive = true;
									var obj3 = {
										name : item3.name,
										hidden : hidden,
										pid : item3.pid,
										path : item3.path,
										component : item3.component,
										redirect : item3.redirect,
										meta: item3.meta,
										type: item3.type,
										linkurl:item3.linkurl
									}
									crr.push(obj3);
								})
							}
							const hidden = item2.hidden == 1 ? true : false;
							item2.meta.keepAlive = true;
							var obj2 = {
								name : item2.name,
								hidden : hidden,
								pid : item2.pid,
								path : item2.path,
								component : item2.component,
								redirect : item2.redirect,
								meta: item2.meta,
								type: item2.type,
								linkurl:item2.linkurl,
								children:crr
							}
							arr.push(obj2);
							
						})
						const alwaysShow = item.alwaysShow == 1 ? true : false;
						const hide = item.hidden == 1 ? true : false;
						var obj = {
							name : item.path,
							path : item.path,
							component : item.component,
							alwaysShow : alwaysShow,
							hidden : hide,
							redirect : item.redirect,
							meta: item.meta,
							children: arr,
							type: item.type,
							linkurl:item.linkurl
						}
						newRoute.push(obj);
					})
					const rewriteRoutes = filterAsyncRoutes(newRoute);
					setRoutes(rewriteRoutes);
					resolve(rewriteRoutes)
				}
			})
			.catch((error) => {
			reject(error);
			});
		});
	}
  	return { routes, setRoutes, generateRoutes };
	
});
// 非setup
export function usePermissionStoreHook() {
  	return usePermissionStore(store);
}
